package com.xinxin.socket.handler;

import com.xinxin.socket.context.ChannelContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@io.netty.channel.ChannelHandler.Sharable
public final class ChannelHandler extends ChannelInboundHandlerAdapter {

    private static final ChannelHandler INSTANCE = new ChannelHandler();

    private final ChannelContext channelContext = ChannelContext.getInstance();

    private ChannelHandler() {
    }

    public static ChannelHandler getInstance() {
        return INSTANCE;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("Channel connected: {}", ctx.channel().toString());
        channelContext.channelActive(ctx);

        ctx.fireChannelActive();

        ctx.channel().closeFuture().addListener(future -> {
            log.info("Channel disconnected: {}", ctx.channel().toString());
            channelContext.channelInactive(ctx);
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("channel error", cause);
        ctx.close();
    }
}
